<?php


   require_once($config['app_dir'] . '/classes/staff.class.php');
   //require_once($config['app_dir'] . '/classes/class.mysql.php');
   //require_once($config['app_dir'] . '/includes/mailer.class.php');
   require_once($config['app_dir'] . '/includes/template.class.php');
   require_once($config['app_dir'] . '/includes/auxiliary.class.php');

   require_once($config['app_dir'] . '/includes/db.class.php');
   require_once($config['app_dir'].'/classes/class.mailshots.php');
   //------------------------------------------------------------------------------------------------
   class objUserAdmin  {
   		var $userTable = "fa_users";
   		var $db;
   		var $UserDataArr = Array();
   		var $totalUsers = 0;
   		var $activeUsers = 0;
   		var $subscrUsers = 0;
   		var $mailModes = Array("EmailTrial","EmailServiceCost","EmailNegativePerf","EmailOldUsers");
   		var $subscrDaysLeft = 0;
   		var $regWithin7 = 0;
   		var $actWithin7 = 0;
   		var $regYesterday = 0;
   		var $actYesterday = 0;
   		var $activeSubscribers = 0;
   		var $updateActivation=0;
   		var $forecastsLoaded = 1;
   		var $recordsPerPage = 500;
   		var $pagingData;
   		var $is2w = false;

		function __construct() {

			$db = $this->db = objDataBase::GetInstance();//new objDataBase();
			$this->pagingData = objAuxiliary::getPagingData($this->countUsers(),$this->recordsPerPage);
			echo count($this->pagingData);
      	} //constructor

      public function getUserData() {
         if( !$this->db ) return false;
         if ($_GET['table']) $this->userTable = $_GET['table'];

		//limit conditions if page set
         if (!$_GET['start']) $limitStart = 0;
         else $limitStart = $_GET['start'];

		//paging only for extended userstats
         if ($_GET['p']!="usertotals") $limitConditions = " LIMIT ".$limitStart.",".$this->recordsPerPage;

		if (!$_GET['query']){
         $query = "SELECT UserID,Name,Login,Password,GroupID,RegistrationTime,ActivationTime ".
         		"FROM ".$this->userTable." ORDER BY UserID desc".$limitConditions;
         } else{
         	switch ($_GET['query']){
         		case "2w2w":
            	//$query = "SELECT u.UserID, u.Name, u.Login, u.Password, u.GroupID, u.RegistrationTime, u.ActivationTime, ".
            	//"s.subscr_id, s.subscr_time, s.subscr_period, s.subscr_status ".
         		//"FROM fa_subscriptions s LEFT JOIN fa_users u ON s.user_id=u.UserID ".
         		//"WHERE u.UserID is not null ".
         		//"AND (((s.subscr_time+s.subscr_period*86400)-UNIX_TIMESTAMP())/86400) < 14  ".
         		//"AND (((s.subscr_time+s.subscr_period*86400)-UNIX_TIMESTAMP())/86400) > (-14) ".
         		//" ORDER BY u.UserID asc, s.subscr_time desc"; //GROUP BY s.user_id

         		$query = "SELECT s.subscr_period, u.UserID, u.Name, u.Login, u.Password, u.GroupID, u.RegistrationTime, u.ActivationTime, ".
         		"if (s.subscr_active=1, round( (s.subscr_period*86400 - (UNIX_TIMESTAMP() - s.subscr_time))/86400 ), ".
         			"if (s.subscr_status='subscr_eot', round((s.subscr_time - UNIX_TIMESTAMP())/86400), ".
         			"round(( (s.subscr_time - UNIX_TIMESTAMP()) + s.subscr_period*86400 )/86400) ) ".
         		") as days,  ".
         			//"round(( (s.subscr_time - UNIX_TIMESTAMP()) + s.subscr_period*86400 )/86400) ) ) as days,  ".
         		//"if ( round( ( (s.subscr_time - UNIX_TIMESTAMP()) + s.subscr_period*86400 )/86400 )) as days,  ".
            	"s.subscr_id, s.subscr_time, s.subscr_period, s.subscr_status, subscr_active ".
         		"FROM fa_subscriptions s LEFT JOIN fa_users u ON s.user_id=u.UserID ".
         		//W"WHERE u.UserID is not null".
         		"  ORDER BY u.UserID desc, s.subscr_time desc"; //GROUP BY s.user_id
         		$this->is2w = true;
         		break;
         	}
         }



         try {
           $rs = $this->db->Execute($query);

         } catch(exception $e) {
         	$this->db->debug = true;
            if (true == $this->db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }


            $cnter = 0;
            while (!$rs->EOF) {

            	if ($_GET['query']=='2w2w'){
                    $subscr_id = explode("_",$rs->fields['subscr_id']);
                    $subscr_time = $subscr_id[2];

             		//if ($rs->fields['subscr_status']!='subscr_eot'){
             			$sDaysLeft = intval((($subscr_time + $rs->fields['subscr_period']*86400) - time())/86400);
               			//$sDaysLeft = intval((($rs->fields['subscr_time']+$rs->fields['subscr_period']*86400)-time())/86400);
               		//} else {
                		//$sDaysLeft = intval((($rs->fields['subscr_time']-$rs->fields['subscr_period']*86400)-time())/86400);
                	//}
                    //echo  $sDaysLeft;
                	//if($sDaysLeft>14 || $sDaysLeft<(1-15)) $rs->MoveNext();
         		}
            	$actSubscrFlag = false;
                //$rs->fields['activated']="activated";
                $this->UserDataArr[$cnter]['userid'] = $rs->fields['UserID'];
                $this->UserDataArr[$cnter]['name'] = $rs->fields['Name'];
                $this->UserDataArr[$cnter]['email'] = $rs->fields['Login'];
                $this->UserDataArr[$cnter]['psswd'] = $rs->fields['Password'];
                $this->UserDataArr[$cnter]['days'] = $rs->fields['days']; //subscription days left/passed
                $this->UserDataArr[$cnter]['group'] = objStaff::getUserGroup($rs->fields['GroupID']);
                $this->UserDataArr[$cnter]['registered'] = $this->getRegistrationDate($rs->fields['RegistrationTime']);
                $this->UserDataArr[$cnter]['activated'] = $this->getActivationDate($rs->fields['ActivationTime']);
                //$this->UserDataArr[$cnter]['active'] = true;



                if (!$rs->fields['ActivationTime']) {
                	$this->UserDataArr[$cnter]['acttmstmp'] = time();
                	//$this->UserDataArr[$cnter]['active'] = false;
                }
                //else if (date("Y-m-d",$rs->fields['ActivationTime'])==date("Y-m-d",time()))
                	//$this->UserDataArr[$cnter]['acttmstmp'] = time();
                else $this->UserDataArr[$cnter]['acttmstmp'] = $rs->fields['ActivationTime'];

                //$this->UserDataArr[$cnter]['notifications'] = $this->getNotifications($rs->fields['Notifications']);

				// display pips earned by system for every user during their registration
                $this->subscrDaysLeft=0;
                $mshot = new objMailshot();

                if ($mshot->checkSubscribed($rs->fields['UserID'])){
                	// acive users
                	$this->activeSubscribers++;
                	$actSubscrFlag = true;
                    $this->UserDataArr[$cnter]['subscr_period'] = round($rs->fields['subscr_period']);
                	$this->UserDataArr[$cnter]['subscribed'] = "Yes";
                	$this->UserDataArr[$cnter]['subscrflag'] = 1;
                	$this->subscrUsers++;
                	$mshot->getSubscrData($rs->fields['UserID']);
                	// if user subscribed set proper date for earned pips calculation (during subscription)
                	$this->UserDataArr[$cnter]['acttmstmp'] = time() - intval($mshot->subscrDays - $mshot->subscrDaysLeft)*86400;
                	$this->UserDataArr[$cnter]['sDaysLeft'] = $mshot->subscrDaysLeft;
                	$this->UserDataArr[$cnter]['endtmstmp'] = time();
                }
                else {
                	// if user not subscribed but should be displayed for "2weeks after expiration" view
                	if ($_GET['query']=='2w2w'){
                		//if ($rs->fields['subscr_status']!='subscr_eot'){
                			//$this->UserDataArr[$cnter]['sDaysLeft'] = round((($rs->fields['subscr_time']+$rs->fields['subscr_period']*86400)-time())/86400);
                		//} else {
                			//$this->UserDataArr[$cnter]['sDaysLeft'] = round(($rs->fields['subscr_time']-time())/86400);
                		//}
                		$this->UserDataArr[$cnter]['sDaysLeft'] = $rs->fields['days'];
         			}
         			$this->UserDataArr[$cnter]['subscr_period'] = round($rs->fields['subscr_period']);
                	$this->UserDataArr[$cnter]['subscribed'] = "No";
                	$this->UserDataArr[$cnter]['subscrflag'] = 0;
                }

                	if ($_GET['query']=='2w2w'){
                		$this->UserDataArr[$cnter]['sDate'] = " ".$sDaysLeft." ".date("Y-m-d",$rs->fields['subscr_time'])." (".round($rs->fields['subscr_period']/30).")";
         			}

                	if (!$mshot->isTrialFinished($rs->fields['UserID'])){
                		if (!$actSubscrFlag) $this->activeSubscribers++;
                		$this->UserDataArr[$cnter]['ontrial'] = $mshot->trialDaysLeft;
                		$this->UserDataArr[$cnter]['endtmstmp'] = time();
                	}
                	if (!$this->UserDataArr[$cnter]['ontrial'] && $this->UserDataArr[$cnter]['subscrflag']==0) {
                		$this->UserDataArr[$cnter]['endtmstmp'] = $this->UserDataArr[$cnter]['acttmstmp']+14*86400;
                	}


                //$this->UserDataArr[$cnter]['endtmstmp'] = time();

		        $rs->MoveNext();
		        $cnter++;
			}
           $this->totalUsers = $cnter;


        //$this->UserDataArr = $rs->GetArray();
        unset($rs);

        return true;


      } //getUserData

      public function resetUserTrial($userMail) {
         if( !$this->db ) return false;
         $query = "UPDATE LOW_PRIORITY  ".$this->userTable."  SET ActivationTime=UNIX_TIMESTAMP(),TrialNotification=0 WHERE Login='$userMail'";

         try {
           $rs = $this->db->Execute($query);

         } catch(exception $e) {
            if (true == $this->db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }

        return true;


      } //resetUserTrial



      public function countUsers () {
         if( !$this->db ) return false;
         $query = "SELECT COUNT(UserID) as cnt FROM fa_users";

         try {
           $rs = $this->db->Execute($query);

         } catch(exception $e) {
            if (true == $this->db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }

        return $rs->fields['cnt'];


      } //countUsers



      private function getRegistrationDate($date) {
        if (!$date) $date = "&nbsp;";
        else {
        	if ((time()-$date)/86400 <= 7) $this->regWithin7++;
        	$date = date("Y-m-d",$date);
        	$yesterday = date('Y-m-d', mktime(0, 0, 0, date("m") , date("d") - 1, date("Y")));
        	if ($date == $yesterday) $this->regYesterday++;
        }

        return $date;
      } //getRegistrationDate

      private function getActivationDate($date) {
        if (!$date) $date = "-";
        else {
        	//if ((time()-$date)/86400 <= 7) $this->actWithin7++;
        	$date = date("Y-m-d G:i",$date);
        	$this->activeUsers = $this->activeUsers++;
        	//$yesterday = date('Y-m-d', mktime(0, 0, 0, date("m") , date("d") - 1, date("Y")));
        	//if ($date == $yesterday) $this->actYesterday++;
        }


        return $date;
      } //getActivationDate

      private function getNotifications($notifications) {
      	$notificationsArr = Array();
      	if (!$notifications) $notificationsArr = Array("&nbsp;");
      	else{
      		$notifications = explode(",",$notifications);
      		foreach ($notifications as $notification){
      			if ($notification!="") {
                 	$notificationsArr[] = $notification;
         		}
      		}
      	}

        return $notificationsArr;
      } //getNotifications


      public function sendNotifications() {
      	$this->updateActivation = $_POST['action'];
      	$mailshot = new objMailshot();

		$mailshot->mailMode = $this->getMailMode();

      	//$mailshot->getEmailsArr();
      	$mailshot->emailsArr = $this->getUsers2Notify();

        // if system perfomance was negative prolong trial for 2 weeks
        if ($this->updateActivation==1){
	      	foreach ($mailshot->emailsArr as $email){
	      		$this->resetUserTrial($email);
	      	}
      	}

      	$mailshot->getNotificationsData();
   		$mailshot->setMailContent();
   		$mailshot->sendNotifications();
   		//$mailshot->notifyTrialEnd(); //function emails info

        return true;
      } //sendNotifications

      private function getUserGroup($group) {
      	switch ($group){
      		case "0":
      		$groupName = "User";
      		break;
      		case "1":
      		$groupName = "Expert";
      		break;
      		case "2":
      		$groupName = "Auth. Expert";
      		break;
      		case "3":
      		$groupName = "Administrator";
      		break;
      	}

        return $groupName;
      } //getNotifications

      public function getUsers2Notify() {
      	$users2Notify = $_POST['emailsArr'];

        return $users2Notify;
      } //sendNotifications

      public function getMailMode() {
      	$mailMode = $_POST['mailshotMode'];

        return $mailMode;
      } //sendNotifications

      public function loadForecasts() {
      	$mailshot = new objMailshot();
      	$this->forecastsLoaded = $mailshot->getUserPips();
        //return ;
      } //loadForecasts


      public function getUserPips($tmstmp=false,$endtmstmp=false) {

        $userPips = 0;
        $pips = $this->forecastsLoaded;
        $fcsts ="";

        foreach($this->forecastsLoaded as $fcast){
             if($fcast[0]>=$tmstmp && $fcast[0]<=$endtmstmp) {
             	$userPips += $fcast[1];
             	//$fcsts.= $fcast[1]."<br>";
             }
        }



        //return $userPips."<br>".date("Y-m-d",$tmstmp)." ".date("Y-m-d",$endtmstmp);
         //return $userPips."- <br>".$fcsts;
          return $userPips;
      } //getUserPips


       public function getActivationLink($uid,$email) {
        	return "http://www.intelli4x.com/index.php?p=signals&s=confirm&code=".md5($uid.$email);
      } //getUserPips

      public function ProcessAction(){
      	$action = $_GET['action'];
      	$uid = $_GET['uid'];

      	switch($action){
      	case "delete":
      		$this->deleteUser($uid);
      		break;
      	}


        $this->getUserData();
      	return $action;
      }

      private function deleteUser($uid){
      	if( !$this->db ) return false;
         $query = "DELETE FROM  ".$this->userTable." WHERE UserID='$uid'";

         try {
           $rs = $this->db->Execute($query);

         } catch(exception $e) {
            if (true == $this->db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }
      }


      public function setT() {
      	$tstmp = time()- (86400*11);
        $tstmp = date("Y-m-d",1182282905);
        return $tstmp;
      } //sendNotifications
   }



//---------------------------------------------------------------------------------------------------


class objMonthTrial  {
   		var $db;

		function __construct() {

			$db = $this->db = objDataBase::GetInstance();//new objDataBase();
      	} //constructor


       public function getUsersTrials () {
         if( !$this->db ) return false;
         $query = "select count(*) as TotalUsers, FROM_UNIXTIME(RegistrationTime, '%M %Y') as Registered,".
         " FROM_UNIXTIME(RegistrationTime, '%M') as Month ".
         "from fa_users where ActivationTime is not null group by Registered order by RegistrationTime desc";

         try {
           $rs = $this->db->handler->getAll($query);

         } catch(exception $e) {
            if (true == $this->db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }

        return $rs;


      } //countUsers


}






class objTrialUsers  {
   		var $db;

		function __construct() {

			$db = $this->db = objDataBase::GetInstance();//new objDataBase();
      	} //constructor


       public function getTrialsUsers() {
         if( !$this->db ) return false;
         $query = "select UserID, Login,FROM_UNIXTIME(ActivationTime,'%M %d %Y') as ActiveFrom,  round((UNIX_TIMESTAMP() - ActivationTime)/86400) as TrialDays, TrialNotification  ".
         "from fa_users where ActivationTime>UNIX_TIMESTAMP('2008-04-25 00:00:00') and ActivationTime<UNIX_TIMESTAMP('2008-05-17 00:00:00') and Active=1 order by ActivationTime desc";
         //$this->db->debug = true;
         try {
           $rs = $this->db->handler->getAll($query);

         } catch(exception $e) {
            if (true == $this->db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }

        return $rs;


      } //countUsers

      public function resetTrial($userid,$notified) {
         if( !$this->db ) return false;


         if ($notified==1) $update_rule = "(UNIX_TIMESTAMP() - 87000*7)";
         else $update_rule = "(ActivationTime + 87000*7)";


         $query = "update fa_users set ActivationTime = ".$update_rule.",TrialNotification=0 where UserID=".$userid;
         //$this->db->debug = true;
         try {
           $rs = $this->db->handler->Execute($query);

         } catch(exception $e) {
            if (true == $this->db->debug ) {
              adodb_pr($e);
              $e = adodb_backtrace($e->trace);
            }
            die('DB Error: '.$e->sql);
         }

		if(!$rs) return false;
        return true;


      } //countUsers


}


class objAddMAP  {
   		var $db;

		function __construct() {

			$db = $this->db = objDataBase::GetInstance();//new objDataBase();
      	} //constructor


       public function addMAPrecord () {
       	if ($_POST){
       		$paramNameConst = "name".$_POST['shortName'];
       		$paramDescrConst = "descr".$_POST['shortName'];
       		$paramName = $_POST['fullName'];
       		$paramDescr = $_POST['shortDescr'];
       		$paramSys = $_POST['system'];
       		$paramLot = $_POST['calcLot'];
       		$paramLev = $_POST['calcLeverage'];
       		$paramDep = $_POST['calcDeposit''];
       		$paramRes = "_map_list";


         	$queryMAPinsert = "INSERT INTO fa_map (NameConstant, DescrConstant, SystemID, CalcLot, CalcDeposit, CalcLeverage) VALUES (?,?,?,?,?,?)";
         	$queryMAPconstInsert = "INSERT INTO fa_const (resource, name) VALUES (?,?)";
         	$queryMAPlabelInsert = "INSERT INTO fa_label (language_id, const_id, text) VALUES (?, ".
         	"(SELECT max(id) FROM fa_const), ? )";


           $rs = $this->db->handler->Execute($queryMAPinsert, array($paramNameConst, $paramDescrConst, $paramSys, $paramLot, $paramDep, $paramLev) );

           $rs = $this->db->handler->Execute($queryMAPconstInsert, array($paramRes, $paramNameConst) );
           $rs = $this->db->handler->Execute($queryMAPlabelInsert, array(1, $paramName) );

           $rs = $this->db->handler->Execute($queryMAPconstInsert, array($paramRes, $paramDescrConst) );
           $rs = $this->db->handler->Execute($queryMAPlabelInsert, array(1, $paramDescr) );

        }


        return true;
      } //addMAPrecord



      public function getSystems () {
     	$query = "SELECT SystemID, Name FROM fa_systems ORDER BY SystemID";
      	$rs = $this->db->handler->getAll($query);
   		return $rs;

      } //getSystems


}



 class objUserTracker  {
   		var $db;
   		var $cheetersData = array();
   		var $ipData = array();




		function __construct() {

			$this->db = objDataBase::GetInstance();//new objDataBase();
      	} //constructor


      	public function getCheeterData() {


         	$queryCheeter = "SELECT UserIP, UserHost, count(UserIP) FROM fa_users_tracking GROUP BY UserIP HAVING count(UserIP)>1";
         	$queryData = "SELECT t.UserID, t.UserAgent, u.Name, u.Login, u.ActivationTime as Activated, u.Password".
         	" FROM fa_users_tracking t LEFT JOIN fa_users u ON u.UserID=t.UserID WHERE t.UserIP=?";

			$counter=0;

           $rs = $this->db->handler->Execute($queryCheeter);
	           while (!$rs->EOF) {

                    $this->cheetersData[$counter]["ip"] = $rs->fields["UserIP"];
                    $this->cheetersData[$counter]["host"] = $rs->fields["UserHost"];
	           		$this->cheetersData[$counter]["data"] = $this->db->handler->getAssoc($queryData, array($rs->fields["UserIP"]) );

					$counter++;
	           	 	$rs->MoveNext();
				}

        return true;
        }


        public function getIPData() {

         	$queryData = "SELECT t.UserID, t.UserIP, t.UserHost, t.UserAgent, u.Name, u.Login, u.ActivationTime as Activated, u.Password  FROM fa_users_tracking t LEFT JOIN fa_users u ON u.UserID=t.UserID ORDER BY t.UserID";


          $this->ipData = $this->db->handler->getAll($queryData);



        return $this->ipData;
      } //addMAPrecord




}








?>